package com.cc.chioceFileListView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ygo.feihua.Gongju;
import com.ygo.feihua.R;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.support.v7.app.AppCompatActivity;
import android.widget.RelativeLayout;
import android.widget.Button;

public class ChioceFileView extends LinearLayout{

    ListView fileListView;

    ListViewAdapter fileListViewAdapter;

    LinearLayout pathTextLayout;

    final String DEFAULTPATH = "/mnt/sdcard/";

    ArrayList<String> filePathArrayList = new ArrayList<String>();

    File currentFile;

    OnChioceFileListener mOnChioceFileListener;

    ExecutorService pool;
    
	
    int imageViewWidth = 0;
    
    OnScrollListener onScrollListener;
    
	Gongju gj;

	private Toolbar tool;
	
    static class STRING{
        public static final String CHIOCE_FILE = "选择文件";
        public static final String BACKUP_PATH = "返回上一项 ";
    };

    public ChioceFileView(Context context, AttributeSet attrs) {
        super(context, attrs);
		
		gj=Gongju.getdx(context);
		
		//设置LinearLayout水平或垂直
        setOrientation(LinearLayout.VERTICAL);
		//LinearLayout背景
        setBackgroundColor(Color.WHITE);

        createExecutorService();
        
        fileListView = new ListView(context);
        fileListView.setOnScrollListener(onScrollListener = new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				/*
				 *scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
				 *SCROLL_STATE_IDLE是当屏幕停止滚动时
				 *SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时
				 *SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
				*/
				//屏幕停止滚动时显示图片
				if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
					cancleExecutorService();
					createExecutorService();
					int allItemNumber = fileListView.getChildCount();
					View itemView;
					for(int i = 0 ; i < allItemNumber ; i ++){
						itemView = fileListView.getChildAt(i);
						if(itemView == null){
							return;
						}
						int index = fileListView.getFirstVisiblePosition() + i;
						String path = filePathArrayList.get(index).toString();
						if(new File(path).isDirectory()){
							continue;
						}
						final ViewHolder viewHolder = (ViewHolder) itemView.getTag();
		                if(path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".bmp")){
		                	LoadBitmapThread loadBitmapThread= new LoadBitmapThread(getContext(), filePathArrayList.get(index).toString(), imageViewWidth, new OnBitmapLoadOkListener() {
		    					
		    					@Override
		    					public void onLoadFinish(Bitmap bitmap) {
		    						// TODO Auto-generated method stub
		    						viewHolder.imageView.setImageBitmap(bitmap);
		    					}
		    					
		    					@Override
		    					public void onLoadFail() {
		    						// TODO Auto-generated method stub
		    						//viewHolder.imageView.setImageBitmap(fileBitmap);
		    					}
		    				});
		                	if(!pool.isShutdown()){
		                		pool.execute(loadBitmapThread);
		                	}
		                }
					}
					
				}else{
					cancleExecutorService();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}
		});
        fileListView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1000));
		
        fileListView.setAdapter(fileListViewAdapter = new ListViewAdapter(getContext() ,filePathArrayList, imageViewWidth = dpToPx(50), createFolderBitmap(imageViewWidth), createFileBitmap(imageViewWidth)));
        fileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                File file = new File(filePathArrayList.get(position));
                boolean isReData = refershListViewContext(file.toString());
                if (!isReData && new File(filePathArrayList.get(position)).isDirectory()) {
                    Toast.makeText(getContext(), "folder context by Null", Toast.LENGTH_LONG).show();
                }
                if(mOnChioceFileListener != null && file.isFile()){
                    mOnChioceFileListener.onChioceFile(getId(), file);
                }
            }
        });
        
        pathTextLayout = new LinearLayout(context);
        pathTextLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dpToPx(50)));
        pathTextLayout.setOrientation(LinearLayout.HORIZONTAL);
        pathTextLayout.setBackgroundColor(Color.WHITE);
        pathTextLayout.setGravity(Gravity.CENTER);
        pathTextLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = currentFile.getParentFile();
				
                if (file != null) {
                    refershListViewContext(file.toString());
                } else {
                    Toast.makeText(getContext(), "没有上一级目录", Toast.LENGTH_LONG).show();
                }
            }
        });
        TextView textView = new TextView(context);
        textView.setTextSize(20);
        textView.setText(STRING.BACKUP_PATH);
        textView.setTextColor(Color.BLUE);
        pathTextLayout.addView(textView);

        LinearLayout tieltLayout = new LinearLayout(context);
        tieltLayout.setGravity(Gravity.CENTER);
        TextView titleTextView = new TextView(context);
        titleTextView.setTextSize(20);
        titleTextView.setText(STRING.CHIOCE_FILE);
        titleTextView.setTextColor(Color.BLUE);
        tieltLayout.addView(titleTextView);
        tieltLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dpToPx(50)));

        View lin = new View(context);
        lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dpToPx(1)));
        View lin2 = new View(context);
        lin2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dpToPx(1)));
        lin.setBackgroundColor(Color.parseColor("#008cf9"));
        lin2.setBackgroundColor(Color.parseColor("#008cf9"));

		 tool=(Toolbar) LayoutInflater.from(context).inflate(R.layout.toolbar,null);
		
		tool.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		
		
		//添加标题栏
        addView(tool);
		//添加分割线
        addView(lin);
		//添加listview
        addView(fileListView);
		//添加分割线2
        addView(lin2);
		//添加底部返回上一级
        addView(pathTextLayout);

        refershListViewContext(DEFAULTPATH);
    }

    @Override
    protected void onDetachedFromWindow() {
    	// TODO Auto-generated method stub
    	super.onDetachedFromWindow();
    	cancleExecutorService();
    	if(fileListViewAdapter != null){
    		fileListViewAdapter.recycle();
    	}
    }
    
    void createExecutorService(){
    	pool = Executors.newSingleThreadExecutor();
    }
    void cancleExecutorService(){
    	try {
    		pool.shutdownNow();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
    
    boolean refershListViewContext(String filePath){
    	cancleExecutorService();
        if(filePath == null){
            return false;
        }
        File file = new File(filePath);
        if(file == null || !file.exists() || !file.canRead()){
            return false;
        }
        File[] files = file.listFiles();
        if(files == null || files.length <= 0){
            return false;
        }
        currentFile = file;
        filePathArrayList.clear();
        for(File object : files){
            filePathArrayList.add(object.toString());
        }
        ListSort.listSort(filePathArrayList);
        fileListViewAdapter.notifyDataSetInvalidated();
        fileListView.setSelection(0);
        fileListView.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				onScrollListener.onScrollStateChanged(null, OnScrollListener.SCROLL_STATE_IDLE);
			}
		});
        return true;
    }

    public  int dpToPx(int dp){
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int)(dp * density + 0.5f);
    }

    /** ����ļ���ͼ��λͼ **/
    public Bitmap createFolderBitmap(int widthAndHeight){
        Bitmap bitmap = Bitmap.createBitmap(widthAndHeight, widthAndHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(dpToPx(1));
        paint.setColor(Color.BLACK);
        canvas.drawRect(widthAndHeight / 4, (int) (widthAndHeight / 2.5), widthAndHeight / 4 * 3, widthAndHeight / 4 * 3, paint);
        canvas.drawRect(widthAndHeight / 4, widthAndHeight / 3, (int) (widthAndHeight / 4 * 2.2), (int) (widthAndHeight / 2.5), paint);
        return bitmap;
    }
    /** ����ļ�ͼ��λͼ **/
    public Bitmap createFileBitmap(int widthAndHeight){
        Bitmap bitmap = Bitmap.createBitmap(widthAndHeight, widthAndHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(dpToPx(1));
        paint.setColor(Color.BLACK);
        int top = widthAndHeight / 5;
        int bottom = widthAndHeight / 5 * 4;
        int left = widthAndHeight / 4;
        int right = widthAndHeight / 4 * 3;
        canvas.drawRect(left, top, right, bottom, paint);
        paint.setStyle(Paint.Style.FILL);
        int textSize = (int)(getContext().getResources().getDisplayMetrics().scaledDensity * 20 + 0.5f);
        paint.setTextSize(textSize);
        canvas.drawText("?", widthAndHeight/2 - textSize/2/2, widthAndHeight/2 + textSize/2, paint);
        return bitmap;
    }

    public void setOnChioceFileListener(OnChioceFileListener listener){
        this.mOnChioceFileListener = listener;
    }

	public void setDefaultPath(String getenv) {
		// TODO Auto-generated method stub
		refershListViewContext(getenv);
	}

	
	public Toolbar getTool(){
		return tool;
	}
	public File getfile(){
		return currentFile;
	}
}
